<template>

  <el-container>
    <!-- 头部 -->
    <el-header>
      <el-page-header @back="goBack" content="电子围栏绘制">
      </el-page-header>
    </el-header>

    <!-- 中间 -->
    <el-main>
      <!-- 地图 -->
      <div id="map-container"></div>

      <!-- 右侧操作区 -->
      <div class="s-control-r">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="" style="margin-right:30px;">
            <el-input v-model.lazy="keyword" placeholder="请输入地名" prefix-icon="el-icon-search" clearable>
            </el-input>
          </el-form-item>
          <el-form-item label="">
            <el-radio-group v-model="radioSelect" size="mini">
              <el-radio-button label="none"><span class="s-icon s-icon-select"></span></el-radio-button>
              <el-radio-button label="circle"><span class="s-icon s-icon-circle"></span>
              </el-radio-button>
              <el-radio-button label="polygon"><span class="s-icon s-icon-polygon"></span>
              </el-radio-button>
              <el-radio-button label="rectangle"><span class="s-icon s-icon-rectangle"></span>
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
          <!-- 地区检索显示区 -->
          <div id="search-result"></div>
        </el-form>
      </div>
    </el-main>

    <!-- 尾部 -->
    <el-footer>
      <el-row type="flex" class="row-bg" justify="end" style="margin:14px 0 0 0;">
        <el-button type="" size="small" style="margin-left:20px;" @click="goBack">返回</el-button>
        <el-button type="primary" size="small" style="margin-left:20px;" @click="saveHurdle">保存</el-button>
      </el-row>
    </el-footer>
  </el-container>

</template>
<script>
import {addPosition} from "@/api/gpl/fence";
export default {
  name: "index",

  data() {
    return {
      name: "draw",
      center: { lng: 116.93761, lat: 40.059866 }, // 中心点坐标
      zoom: 11, // 缩放级别
      location: "吉安市",
      keyword: "",
      radioSelect: "none",
      styleOptions: {
        strokeColor: "#5E87DB", // 边线颜色
        fillColor: "#5E87DB", // 填充颜色。当参数为空时，圆形没有填充颜色
        strokeWeight: 2, // 边线宽度，以像素为单位
        strokeOpacity: 1, // 边线透明度，取值范围0-1
        fillOpacity: 0.2, // 填充透明度，取值范围0-1
      },
      labelOptions: {
        borderRadius: "2px",
        background: "#FFFBCC",
        border: "1px solid #E1E1E1",
        color: "#703A04",
        fontSize: "12px",
        letterSpacing: "0",
        padding: "5px",
      },
      map: null, // 百度地图
      drawingManager: null, // 鼠标绘制工具
      localSearch: null, // 地区检索
      region: {}, // 行政区域
    };
    id:0;
  },

  watch: {
    // 绘制类型变更
    radioSelect(nval, oval) {
      if (nval != "none") {
        this.clearOverlays();
        this.drawingManager.close();
        this.draw(nval);
      } else {
        this.drawingManager.close();
      }
    },
    // 地区检索关键字变更
    keyword(nval, oval) {
      this.localSearch.clearResults();
      this.localSearch.search(nval);
    },
  },

  mounted() {
    // 创建Map实例
    this.map = new BMap.Map("map-container", {
      enableMapClick: false,
      minZoom: 5,
      maxZoom: 15,
    });
    // 设置中心点坐标和地图级别
    this.map.centerAndZoom(
      new BMap.Point(this.center.lng, this.center.lat),
      this.zoom
    );
    // 开启鼠标滚轮缩放
    this.map.enableScrollWheelZoom(true);

    // 创建鼠标绘制工具
    this.drawingManager = new BMapLib.DrawingManager(this.map, {
      // isOpen: true, //是否开启绘制模式
      enableCalculate: true, // 绘制是否进行测距(画线时候)、测面(画圆、多边形、矩形)
      drawingToolOptions: {
        enableTips: true,
        customContainer: "selectbox_Drawing",
        hasCustomStyle: true,
        offset: new BMap.Size(5, 5), // 偏离值
        scale: 0.8, // 工具栏缩放比例
        drawingModes: [
          BMAP_DRAWING_RECTANGLE,
          BMAP_DRAWING_POLYGON,
          BMAP_DRAWING_CIRCLE,
        ],
      },
      enableSorption: true, // 是否开启边界吸附功能
      sorptionDistance: 20, // 边界吸附距离
      enableGpc: true, // 是否开启延边裁剪功能
      enbaleLimit: true, // 是否开启超限提示
      // limitOptions: {
      //     area: 50000000 // 面积超限值
      // },
      circleOptions: this.styleOptions, // 圆的样式
      polylineOptions: this.styleOptions, // 线的样式
      polygonOptions: this.styleOptions, // 多边形的样式
      rectangleOptions: this.styleOptions, // 矩形的样式
      labelOptions: this.labelOptions, // label的样式
    });

    // 实例化地区检索
    this.localSearch = new BMap.LocalSearch(this.map, {
      renderOptions: { map: this.map, panel: "search-result" },
    });

    // 加载围栏数据
    this.loadHurdle();
  },

  methods: {
    // 清除地图覆盖物
    clearOverlays() {
      this.map.clearOverlays();
    },

    // 绘制圆、矩形、多边形
    draw(type) {
      var arr = document.getElementsByClassName("bmap-btn");
      for (var i = 0; i < arr.length; i++) {
        arr[i].style.backgroundPositionY = "0";
      }
      switch (type) {
        case "marker": {
          var drawingType = BMAP_DRAWING_MARKER;
          break;
        }
        case "polyline": {
          var drawingType = BMAP_DRAWING_POLYLINE;
          break;
        }
        case "rectangle": {
          var drawingType = BMAP_DRAWING_RECTANGLE;
          break;
        }
        case "polygon": {
          var drawingType = BMAP_DRAWING_POLYGON;
          break;
        }
        case "circle": {
          var drawingType = BMAP_DRAWING_CIRCLE;
          break;
        }
      }
      // 进行绘制
      if (
        this.drawingManager._isOpen &&
        this.drawingManager.getDrawingMode() === drawingType
      ) {
        this.drawingManager.close();
      } else {
        this.drawingManager.setDrawingMode(drawingType);
        this.drawingManager.open();
      }
    },

    // 绘制行政区域
    drawRegion() {
      if (!this.region.value) {
        this.$message({
          message: "操作失败，请选择区域",
          type: "error",
        });
        return;
      }
      this.radioSelect = "none";
      var bdary = new BMap.Boundary();
      bdary.get(this.region.value, (rs) => {
        //获取行政区域
        this.map.clearOverlays(); //清除地图覆盖物
        var count = rs.boundaries.length; //行政区域的点有多少个
        if (count === 0) {
          alert("未能获取当前输入行政区域");
          return;
        }
        var pointArray = [];
        for (var i = 0; i < count; i++) {
          console.log(rs.boundaries[i]);
          var ply = new BMap.Polygon(rs.boundaries[i], this.styleOptions); //建立多边形覆盖物
          var str = JSON.stringify(ply.ia); //将BMap获取的行政区边界经纬度转为字符串
          this.map.addOverlay(ply); //添加覆盖物
          pointArray = pointArray.concat(ply.getPath());
        }
        this.map.setViewport(pointArray); //调整视野
      });
    },

    // 返回
    goBack() {},

    // 切换地区
    regionChange(data) {
      this.region = data.area || data.city || data.province || {};
    },

    // 加载围栏数据
    async loadHurdle() {
      const {
        data: { points },
      } = await this.$http.get("/api/getCurrent");
      var pointsArr = JSON.parse(points);
      var pathArr = [];
      pointsArr.forEach((item) => {
        var ply = new BMap.Polygon(item, this.styleOptions); //建立多边形覆盖物
        this.map.addOverlay(ply); //添加覆盖物
        pathArr = pathArr.concat(ply.getPath());
      });
      this.map.setViewport(pathArr); //调整视野
    },

    // 保存围栏数据
    saveHurdle() {
      var overlays = this.map.getOverlays();
      var pointsStrArr = [];
      overlays.forEach((item) => {
        if (item.getPath) {
          var pointsStr = this.pointsToStr(item.getPath());
          pointsStr && pointsStrArr.push(pointsStr);
        }
      });
      if (pointsStrArr.length == 0) {
        this.$message({
          message: "操作失败，您没用绘制任何有效区域",
          type: "error",
        });
        return;
      }

      // 后台保存需要的路径坐标数据
      const data = "["+pointsStrArr+"]";
      alert(data);
      this.id=this.$route.query.Id;
      addPosition(this.id,data).then((res)=>{
        alert("添加成功")
        this.$router.push("/tab/fence")
      })
    },

    // 坐标点数组转字符串
    pointsToStr(points) {
      if (!points) return "";
      var str = "";
      points.forEach((item) => {
        str += "["+item.lng + "," + item.lat + "],";
      });
      return str.slice(0, -1);
    },
  },
};
</script>

<style>
.el-container {
  height: 100%;
}

.el-main {
  position: relative;
  padding: 0;
}

.el-page-header,
.el-footer {
  line-height: 60px;
}

.rg-select__el {
  background: #ffffff !important;
}

#map-container {
  width: 100%;
  height: 100%;
}

#search-result {
  width: 400px;
}

.s-control-l {
  display: flex;
  flex-direction: row;
  position: absolute;
  left: 30px;
  top: 30px;
  z-index: 999;
}

.s-control-r {
  display: flex;
  flex-direction: row;
  position: absolute;
  right: 30px;
  top: 30px;
  z-index: 999;
}

.s-search {
  width: 400px;
}

.s-icon {
  display: inline-block;
  width: 24px;
  height: 24px;
  background-size: 100% 100%;
  background-repeat: no-repeat;
}

.s-icon.s-icon-select {
  background-image: url();
}
.el-radio-button.is-active .s-icon.s-icon-select {
  background-image: url();
}

.s-icon.s-icon-circle {
  background-image: url();
}
.el-radio-button.is-active .s-icon.s-icon-circle {
  background-image: url();
}

.s-icon.s-icon-polygon {
  background-image: url();
}
.el-radio-button.is-active .s-icon.s-icon-polygon {
  background-image: url();
}
.s-icon.s-icon-rectangle {
  background-image: url();
}
.el-radio-button.is-active .s-icon.s-icon-rectangle {
  background-image: url();
}
</style>
